package com.lagou.servlet;

import com.lagou.factory.BeanFactory;
import com.lagou.pojo.Result;
import com.lagou.service.TransferService;
import com.lagou.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    private TransferService transferService;

    public TransferServlet() throws Exception {
    }

    @Override
    public void init() throws ServletException {
        try {
            // 在这里拿到当前根目录的地址
            String p = this.getServletContext().getRealPath("/");
            // 实例化Bean工厂
            BeanFactory beanFactory = new BeanFactory("com.lagou", p + "WEB-INF/classes/com/lagou", new String[]{"servlet"});
            // 获取转账服务的实例
            transferService = (TransferService) beanFactory.getBean("transferService");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 执行转账操作
        req.setCharacterEncoding("UTF-8");
        String fromCardId = req.getParameter("fromCardId");
        String toCardId = req.getParameter("toCardId");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            transferService.transfer(fromCardId, toCardId, money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
